import { game } from "../Game";
import { ref, onMounted, onUnmounted } from "@vue/runtime-core";

/**
 * @description 键盘移动
 * @param x 初始化 x 坐标
 * @param y 初始化 y 坐标
 * @param speed 移动速度
 */

// 定义数据结构——上下为一组。左右为一组
const commandType = {
  upAndDown: 'upAndDown',
  leftAndRight: 'leftAndRight'
}

// 飞机移动函数
export const useKeyboardMove = ({ x, y, speed }) => {
  // 坐标
  const moveX = ref(x);
  const moveY = ref(y);

  // 飞行方向数组
  const moveCommand = []

  // 定义类型
  const downCommand = {
    type: commandType.upAndDown,
    dir: 1,
    id: 1
  }

  const upCommand = {
    type: commandType.upAndDown,
    dir: -1,
    id: 2
  }

  const leftCommand = {
    type: commandType.leftAndRight,
    dir: -1,
    id: 3
  }

  const rightCommand = {
    type: commandType.leftAndRight,
    dir: 1,
    id: 4
  }

  const findUpAndDownCommand = () => moveCommand.find((command) => command.type === commandType.upAndDown)
  

  const findLeftAndRightCommand = () => moveCommand.find((command) => command.type === commandType.leftAndRight)
  

  const isExistCommand = (command) => {
    const id = command.id;
    const result = moveCommand.find((c) => c.id === id)
    if (result) return true
    return false
  }

  const removeCommand = (command) => {
    const id = command.id;
    const index = moveCommand.findIndex((c) => c.id === id)
    moveCommand.splice(index, 1)
  }

  const handlerTicker = () => {
    const upAndDownCommand = findUpAndDownCommand()
    if (upAndDownCommand) {
      console.log('1111');
      moveY.value += speed * upAndDownCommand.dir
    }

    const leftAndRightCommand = findLeftAndRightCommand()
    if (leftAndRightCommand) {
      moveX.value += speed * leftAndRightCommand.dir
    }
  }

  const commandMap = {
    ArrowLeft: leftCommand,
    ArrowRight: rightCommand,
    ArrowUp: upCommand,
    ArrowDown: downCommand
  }

  const handleKeyDown = (e) => {
    const command = commandMap[e.code]
    if (command && !isExistCommand(command)) {
      moveCommand.unshift(command)
      console.log(command, moveCommand);
    }
  }

  const handleKeyUp = (e) => {
    const command = commandMap[e.code]
    if (command) {
      removeCommand(command)
    }
  }

  onMounted(() => {
    game.ticker.add(handlerTicker)
    window.addEventListener("keydown", handleKeyDown)
    window.addEventListener("keyup", handleKeyUp)
  })

  onUnmounted(() => {
    game.ticker.remove(handlerTicker)
    window.removeEventListener("keydown", handleKeyDown)
    window.removeEventListener("keyup", handleKeyUp)
  })

  return {
    x: moveX,
    y: moveY
  }
}